package org.dromara.system.service.impl;

import com.github.therapi.runtimejavadoc.repack.com.eclipsesource.json.ParseException;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.WbCompanyInfo;
import org.dromara.system.domain.WbPowerCircle;
import org.dromara.system.domain.WbProvince;
import org.dromara.system.domain.dto.WbCompanyBlacklistCountProductDTO;
import org.dromara.system.domain.dto.WbCompanyBlacklistCountProvinceDTO;
import org.dromara.system.domain.vo.WbProvinceVo;
import org.dromara.system.mapper.WbCompanyInfoMapper;
import org.dromara.system.mapper.WbProvinceMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.WbCompanyBlacklistBo;
import org.dromara.system.domain.vo.WbCompanyBlacklistVo;
import org.dromara.system.domain.WbCompanyBlacklist;
import org.dromara.system.mapper.WbCompanyBlacklistMapper;
import org.dromara.system.service.IWbCompanyBlacklistService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.dromara.system.utils.ImportExcelUtil;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 企业黑名单Service业务层处理
 *
 * @author Lion Li
 * @date 2024-03-22
 */
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class WbCompanyBlacklistServiceImpl implements IWbCompanyBlacklistService {

    private final WbCompanyBlacklistMapper baseMapper;

    private final WbProvinceMapper wbProvinceMapper;

    private final WbCompanyInfoMapper wbCompanyInfoMapper;

    /**
     * 查询企业黑名单
     */
    @Override
    public WbCompanyBlacklistVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询企业黑名单列表
     */
    @Override
    public TableDataInfo<WbCompanyBlacklistVo> queryPageList(WbCompanyBlacklistBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyBlacklist> lqw = buildQueryWrapper(bo);
        Page<WbCompanyBlacklistVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询企业黑名单列表
     */
    @Override
    public List<WbCompanyBlacklistVo> queryList(WbCompanyBlacklistBo bo) {
        LambdaQueryWrapper<WbCompanyBlacklist> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WbCompanyBlacklist> buildQueryWrapper(WbCompanyBlacklistBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WbCompanyBlacklist> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), WbCompanyBlacklist::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getDisposeWay()), WbCompanyBlacklist::getDisposeWay, bo.getDisposeWay());
        lqw.eq(bo.getProvinceId() != null, WbCompanyBlacklist::getProvinceId, bo.getProvinceId());
        lqw.eq(bo.getStatus() != null, WbCompanyBlacklist::getStatus, bo.getStatus());
        lqw.ge(bo.getBlacklistPubTime() != null, WbCompanyBlacklist::getBlacklistPubTime, bo.getBlacklistPubTime());
        lqw.ge(bo.getBlacklistStartTime() != null, WbCompanyBlacklist::getBlacklistStartTime, bo.getBlacklistStartTime());
        lqw.le(bo.getBlacklistEndTime() != null, WbCompanyBlacklist::getBlacklistEndTime, bo.getBlacklistEndTime());
//
        return lqw;
    }

    /**
     * 新增企业黑名单
     */
    @Override
    public Boolean insertByBo(WbCompanyBlacklistBo bo) {
        /**
         * WbItemInfo add = MapstructUtils.convert(bo, WbItemInfo.class);
         *         validEntityBeforeSave(add);
         *         boolean flag = baseMapper.insert(add) > 0;
         *         if (flag) {
         *             bo.setId(add.getId());
         *         }
         *         return flag;
         */


        WbCompanyBlacklist add = MapstructUtils.convert(bo, WbCompanyBlacklist.class);
        validEntityBeforeSave(add);
        Long provinceId = add.getProvinceId();
//        add.setCity(wbProvinceVo.getProvinceName());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改企业黑名单
     */
    @Override
    public Boolean updateByBo(WbCompanyBlacklistBo bo) {
        WbCompanyBlacklist update = MapstructUtils.convert(bo, WbCompanyBlacklist.class);
        validEntityBeforeSave(update);
        Long provinceId = update.getProvinceId();
        WbProvinceVo wbProvinceVo = wbProvinceMapper.selectVoById(provinceId);
//        update.setCity(wbProvinceVo.getProvinceName());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WbCompanyBlacklist entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除企业黑名单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R updateAllList(MultipartFile file) {
        List<WbCompanyBlacklist> tbZbzsList = new ArrayList<>();
        int num = 0;
        try {
            //验证文件类型
            if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls") && !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")) {
                throw new Exception("文件类型有误！请上传Excel文件");
            }
            //获取数据
            List<List<Object>> olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
            List cityList = new ArrayList();
            //封装数据
            for (int i = 0; i < olist.size(); i++) {
                List<Object> list = olist.get(i);
                WbCompanyBlacklist wbCompanyBlacklist = new WbCompanyBlacklist();
                /**
                 * 获取省份id
                 */
                String city = (String) list.get(1);
                if (city != null){
                    Long id = wbProvinceMapper.selectName(city);
                    wbCompanyBlacklist.setProvinceId(id);
                }

                //公司名称
                wbCompanyBlacklist.setCompanyName(String.valueOf(list.get(2)));
                //发布日期blacklistPubTime
                wbCompanyBlacklist.setBlacklistPubTime(String.valueOf(list.get(3)));
                //处理措施disposeWay
                wbCompanyBlacklist.setDisposeWay(String.valueOf(list.get(4)));
                //黑名单开始日期

                //



//                wbCompanyBlacklist.setCity(String.valueOf(list.get(5)));

                wbCompanyBlacklist.setBlacklistPubTime(String.valueOf(list.get(6)));
                String cityName = String.valueOf(list.get(5));
                cityList.add(cityName);
                tbZbzsList.add(wbCompanyBlacklist);
            }
            List<String> distinctCityList = cityList.stream().distinct().toList();
//            List<String> updateCityList=baseMapper.queryDistinctCity();
//            baseMapper.updateAllList(updateCityList);
            num = baseMapper.insertExcelList(tbZbzsList);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail("导入失败，请联系管理员",e);
        }
        return R.ok("导入成功数据条数",num);


    }

    @Override
    public Integer queryListSum(Long companyId) {
        return baseMapper.queryListSum(companyId);
    }

    @Override
    public TableDataInfo<WbCompanyBlacklistCountProvinceDTO> queryCountProvince() {
        List<WbProvinceVo> wbProvinceVos = wbProvinceMapper.selectVoList();
        List<WbCompanyBlacklistCountProvinceDTO> dtos = new ArrayList<>();
        for (WbProvinceVo wbProvinceVo : wbProvinceVos) {
            Long provinceId = wbProvinceVo.getProvinceId();

            WbCompanyBlacklistCountProvinceDTO dto=baseMapper.queryCountProvince(provinceId);
            dtos.add(dto);
        }
        return TableDataInfo.build(dtos);
    }

    @Override
    public  List<WbCompanyBlacklistCountProductDTO> queryCountProduct(String disposeWay) {
        return baseMapper.queryCountProduct(disposeWay);
    }

    @Override
    public TableDataInfo<WbCompanyBlacklistVo> queryPageListZdy(WbCompanyBlacklistBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyBlacklist> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(WbCompanyBlacklist::getStatus);
        Page<WbCompanyBlacklistVo> result = baseMapper.selectVoPageZdy(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WbCompanyBlacklistVo> queryPageListXcx(WbCompanyBlacklistBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyBlacklist> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(WbCompanyBlacklist::getBlacklistPubTime,WbCompanyBlacklist::getId);
        Page<WbCompanyBlacklistVo> result = baseMapper.selectVoPageXcx(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }



    @Override
    public TableDataInfo<WbCompanyBlacklistVo> queryBlackOne(String blacklistStatus,String companyName, PageQuery pageQuery) {
        Page<WbCompanyBlacklistVo> result = baseMapper.queryBlackOne(pageQuery.build(),companyName, blacklistStatus);
        return TableDataInfo.build(result);
    }

}
